1 of 73
2 of 73
Module 1: Basics of Python
Chapter 1:
1.1. Introduction To:
What is Python?
Why are we using Python?
What is an IDE?
What is Anaconda?
Why are we using Anaconda for Python?
What is Jupyter Notebook?
Why are we using Jupyter Notebook?
1.2. Getting Started:
Our First Program in Python
Chapter 2:
2.1 Print Function:
Value
Seperator
End
2.2 Variables
2.3 Basic Data types in Python
Text Type: str, char
Numeric Types: int, float, complex
Boolean Type: True, False
None Type: Nonetype OR None
3 of 73
Chapter 3:
3.1 Operators
3.2 Types of Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Chapter 4:
4.1 Reserved Keywords
4.2 Input Statement
4.3 Comments in Python
Single Line Comments
Multiple Line Comments
4.4 String Formation in Python
‘+’ Formation or String Concatenation
F string
String Formation using format function
4.5 Typecasting in Python
Chapter 5:
5.1 Basic Data Structure in Python
String
List
Tuple
Dictionary
Set/Sets
5.2 Conditional Statements
If
Else
Elif
Nested conditions
5.3 Iteration or Looping Statements
For
o Range
o Enumerators
Nested For
Comprehension
o List Comprehension
o Tuple Comprehension
o Dictionary Comprehension
o Set Comprehension
o Generator Comprehension
While
4 of 73
o Counter
o Flag
o Break
o Continue
o Pass
o Else
While For Combination
5.4 Functions
Def
Return
Default parameters
Args and Kwargs
Global vs Local Variable
Recursion
Lambda function
Generators
Chapter 6:
6.1 Exceptional Handling
Try
Except
Finally
6.2 File Handling.
Open
Write
Read
Append
Close
Chapter 7:
7.1 CSV File
7.2 JSON File
5 of 73
Module 1:
Welcome to the Basics of Python
Chapter 1:
1.1. Introduction To:
What is Python?
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in
data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application
Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple,
easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports
modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive
standard library are available in source or binary form without charge for all major platforms and can be freely distributed.
Why are we using Python?
Python is commonly used for developing websites and software, task automation, data analysis, and data visualization.
Since it's relatively easy to learn, Python has been adopted by many non-programmers such as accountants and scientists,
for a variety of everyday tasks, like organizing finances.
Download from Here!
Now, click the button highlighted below.
6 of 73
Now, wait for the installation to be completed.
Click on '↑' button and then click on 'open'.
Click on 'Install Now' to complete the installation process.
What is an IDE?
An integrated development environment (IDE) is a software application that helps programmers develop software code
efficiently. It increases developer productivity by combining capabilities such as software editing, building, testing, and
packaging in an easy-to-use application. Just as writers use text editors and accountants use spreadsheets, software
developers use IDEs to make their job easier.
Why are IDEs important?
You can use any text editor to write code. However, most integrated development environments (IDEs) include
functionality that goes beyond text editing. They provide a central interface for common developer tools, making the
software development process much more efficient. Developers can start programming new applications quickly instead
of manually integrating and configuring different software. They also don't have to learn about all the tools and can
instead focus on just one application. The following are some reasons why developers use IDEs:
Code editing automation:
Programming languages have rules for how statements must be structured. Because an IDE knows these rules, it contains
many intelligent features for automatically writing or editing the source code.
Syntax highlighting:
An IDE can format the written text by automatically making some words bold or italic, or by using different font colors.
These visual cues make the source code more readable and give instant feedback about accidental syntax errors.
Intelligent code completion:
7 of 73
Various search terms show up when you start typing words in a search engine. Similarly, an IDE can make suggestions to
complete a code statement when the developer begins typing.
Refactoring support:
Code refactoring is the process of restructuring the source code to make it more efficient and readable without changing
its core functionality. IDEs can auto-refactor to some extent, allowing developers to improve their code quickly and easily.
Other team members understand readable code faster, which supports collaboration within the team.
Local build automation:
IDEs increase programmer productivity by performing repeatable development tasks that are typically part of every code
change. The following are some examples of regular coding tasks that an IDE carries out.
Compilation:
An IDE compiles or converts the code into a simplified language that the operating system can understand. Some
programming languages implement just-in-time compiling, in which the IDE converts human-readable code into machine
code from within the application.
Testing:
The IDE allows developers to automate unit tests locally before the software is integrated with other developers' code and
more complex integration tests are run.
Debugging:
Debugging is the process of fixing any errors or bugs that testing reveals. One of the biggest values of an IDE for debugging
purposes is that you can step through the code, line by line, as it runs and inspects code behavior. IDEs also integrate
several debugging tools that highlight bugs caused by human error in real time, even as the developer is typing
What are the types of IDEs
Integrated development environments (IDEs) can be broadly classified into several different categories, depending on the
application development they support and how they work. However, many IDE software applications can fit into multiple
categories. The following are some types of IDEs:
Local IDEs:
Developers install and run local IDEs directly on their local machines. They also have to download and install various
additional libraries depending on their coding preferences, project requirements, and development language. While local
IDEs are customizable and do not require an internet connection once installed, they present several challenges:
They can be time-consuming and difficult to set up. They consume local machine resources and can slow down machine
performance significantly. Configuration differences between the local machine and the production environment can give
rise to software errors.
Cloud IDEs:
Developers use cloud IDEs to write, edit, and compile code directly in the browser so that they don't need to download
software on their local machines. Cloud-based IDEs have several advantages over traditional IDEs. The following are some
of these advantages:
Standardized development environment:
Software development teams can centrally configure a cloud-based IDE to create a standard development
environment. This method helps them avoid errors that might occur due to local machine configuration
differences.
Platform independence:
8 of 73
Cloud IDEs work on the browser and are independent of local development environments. This means they
connect directly to the cloud vendor's platform, and developers can use them from any machine.
Better performance:
Building and compiling functions in an IDE requires a lot of memory and can slow down the developer's computer.
The cloud IDE uses computers resources from the cloud and frees up the local machine’s resources.
How should I choose an IDE?
You can find many modern integrated development environments (IDEs) on the market with a range of features and
different price points. Many IDEs are open source, or free to use and configure. The following are some criteria to consider
when choosing an IDE:
The programming language: The programming language you want to code in often dictates the choice of an IDE.
Dedicated IDEs have automation features that particularly suit the syntax of specific languages. On the other hand, multi-
language IDEs support multiple languages.
The operating system: While most IDEs have multiple versions for different operating systems, they might work better on
specific platforms. For example, some IDEs can perform optimally on the Linux platform but might be slow or difficult to
use on other platforms.
Automation features: The three common features in most IDES are the source code editor, build automation, and
debugger. Additional features may vary and can include the following:
Code editor UI enhancements Automated testing features Code deployment support via plugin integration Code
refactoring support Application packaging support
IDE customization:
Some IDEs include the ability to customize workflows to match a developer's needs and preferences. You can download
and use plugins, extensions, and add-ons to customize your programming experience.
What is Anaconda for Python?
Anaconda Python is a free, open-source platform that allows you to write and execute code in the programming language
Python. It is by continuum.io, a company that specializes in Python development. The Anaconda platform is the most
popular way to learn and use Python for scientific computing, data science, and machine learning. It is used by over thirty
million people worldwide and is available for Windows, macOS, and Linux.
Download from Here!
9 of 73
Why are we using Anaconda for Python?
People like using Anaconda Python because it simplifies package deployment and management. It also comes with a large
number of libraries/packages that you can use for your projects. Since Anaconda Python is free and open source, anyone
can contribute to its development.
Installation:
10 of 73
Click on 'Finish' to complete the installation process.
What is Jupyter Notebook?
The Jupyter Notebook is the original web application for creating and sharing computational documents. It offers a simple,
streamlined, document-centric experience.
Why are we using Jupyter Notebook?
Jupyter Notebook allows users to compile all aspects of a data project in one place making it easier to show the entire
process of a project to your intended audience.
Installing Jupyter:
Project Jupyter’s tools are available for installation via the Python Package Index, the leading repository of software
created for the Python programming language.
This page uses instructions with pip, the recommended installation tool for Python. If you require environment
management as opposed to just installation, look into Conda, mamba, and pipenv.
JupyterLab
pip install jupyterlab
Jupyter Notebook
pip install notebook
11 of 73
Downloading Jupyter-Notebook?
Method 1:
Launch through Anaconda Navigator:
12 of 73
Click on 'Launch' to open!
Method 2:
Launch through Command Prompt (CMD):
Go to 'Cmd', then open the terminal. After that, insert jupyter notebook into it. Press Enter to launch.
13 of 73
Method 3:
Launch directly through Jupyter Notebook itself:
Click on the Icon.
Then, press Enter to launch.
14 of 73
Jupyter Notebook Interface:
15 of 73
16 of 73
17 of 73
Our First Program in Python:
Try it Yourself:
print('Hello world')
Execution of Program:
Chapter 1 ends here!
18 of 73
2.1 Print Function
Chapter 2:
The print () function prints the specified message to the screen, or other standard output device. The message can be a
string, or any other object,
Warning: The object will be converted into a string before written to the screen.
Try it Yourself:
print('Hello world')
Execution of Program:
Value OR Objects: A Value or an object or objects to be printed.
Try it Yourself:
print('This is the value or object! We talked about.')
Execution of Program:
19 of 73
Seperator: Separates the print value by inserting the given value between them.
Try it Yourself:
print('-- Without Seperator --')
print('Python','Pool')
print('--With sep--')
print('Python','Pool',sep='%')
print('--Without sep--')
print(1, 2, 3)
print('--With sep--')
print(1, 2, 3, sep='\n\n')
Execution of Program:
End: The character/string printed at the end after the object.
Try it Yourself:
print('--Without end--')
print('Python','Pool')
print('--With end--')
print('Python','Pool',end='%')
Execution of Program:
20 of 73
2.2 Variables:
A Python Variable is a symbolic name that is a reference or pointer to an object.
Manchester is a variable that holds the value of 1.
Try it Yourself:
Manchester = 1
print(Manchester)
Execution of Program:
2.2 Basic Data types in Python:
Chapter 2 ends here!
21 of 73
Chapter 3:
Operators:
Operators are used to perform various types of operation on variables and values.
Try it Yourself:
For Integer Values:
print(1+2)
For Integer Variables:
a = 1
b = 2
print(a+b)
Execution of Program:
Try it Yourself:
For String Values:
print('John' + 'Doe')
22 of 73
For String Variables:
Firstname = 'John'
Lastname = 'Doe'
print(Firstname+Lastname)
Execution of Program:
Types:
Although, there are many types of operators. but the famous one's are highlighted below:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators:
Arithmetic operators are used to perform arithmetic operations: (+, -, *, /, %)
Try it Yourself:
print(3+3)
print(3-3)
print(3*3)
print(3/3)
print(3%3) # % => Used to perform Remainder operation.
Execution of Program:
23 of 73
Assignment operators:
Assignment operators are used to assign the value we obtained through performing arithmetic operations: (+=, -=, *=, /=,
%=)
Try it Yourself:
x = 1
X
Execution of Program:
Try it Yourself:
x+=2
print(x)
x -= 1
print(x)
x *= 3
print(x)
x /= 2
print(x)
x %= 5
print(x)
Execution of Program:
24 of 73
Comparison operators:
Comparison operators are used in logical statements to determine equality or difference between variables or values. (<,>,
<=,>=,!=, ==)
Try it Yourself:
x = 3
y = 2
print('x=', x,'&','y=', y)
Execution of Program:
Try it Yourself:
x>y #To check if x is greater than y.
y<x #To check if y is lesser than x.
x>=y #To check if x is greater or equals to y.
y<x #To check if y is lesser or equals to x.
x==y # if x equals to y
x! =y # if x does not equal to y
Execution of Program:
25 of 73
Logical operators:
Logical operators are used to check whether the value is true or not. (or, and & not)
Try it Yourself:
x = 1
y = 2
print('x=', x,'&','y=', y)
Execution of Program:
0R:
Returns True, if any of the value is True.
Try it Yourself:
x == 2 or y == 1
x == 2 or y == 2
Execution of Program:
AND:
Returns True, if both values are True.
Try it Yourself:
x == 2 and y == 2
x == 1 and y == 2
Execution of Program:
26 of 73
NOT:
Return reverse (False), If both values are True.
Try it Yourself:
not(x == 1 and y == 2)
not(x == 2 and y == 1)
Execution of Program:
Identity operators:
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the
same memory location: (is, is not)
Try it Yourself:
x is y
x is not y
Execution of Program:
Membership operators:
Membership operators are used to test if a sequence is presented in an object: (in, not in)
Try it Yourself:
x = 'Membership operators are used to test if a sequence is presented in an object'
'are used' in x
'The boy' not in x
Execution of Program:
27 of 73
Bitwise operators:
Bitwise operators work same as logical operators but are used to compare (binary) numbers: (&,|, ~, ^,>>,<<)
Try it Yourself:
x = 1
y = 2
Print bitwise AND operation
print(a & b)
Print bitwise OR operation
print(a | b)
Print bitwise NOT operation
print(~a)
Print bitwise XOR operation
print(a ^ b)
Print bitwise right shift operation
print(a >> 2)
Print bitwise left shift operation
print(a << 2)
Execution of Program:
28 of 73
Chapter 4:
4.1 Reserved Keywords
There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special
language functionality. No object can have the same name as a reserved word.
In Python 3.1 or more, there are 33 reserved keywords:
You can see this list any time by typing help("keywords") to the Python interpreter. Reserved words are case-sensitive and must
be used exactly as shown. They are all entirely lowercase, except for False, None, and True.
4.2 Input Statement
Input statement is used to get input from the user. By default, it returns string(str).
Try it Yourself:
message = input('Enter your name: ')
print(message)
Execution of Program:
29 of 73
4.3 Comments in Python
Comments are used to explain the code. It makes the code more readable and prevents execution when testing code.
Single Line Comment: Comments out all the content which is present on the single line. We use ‘#’ for it.
# Single Line Comment
Execution of Program:
Mutiple Line or Multiline Comment: Comments out all the content which is present on the multiple line. We use ‘’’ ’’’ or “”” “”
for it. Jupyter products doesn’t support multiline comment.
Try it Yourself:
print(""" Multiline Comment """)
Or
print(''' Multiline Comment''')
Execution of Program:
Reminder: Jupyter products doesn’t support multiline comment.
4.4 String Formation in Python
String Formation is used to display all the content into predefined text (a single line).
‘+’ Formation or String Concatenation:
Performing formation through ‘+’ symbol.
Execution of Program:
String Formation using format function:
The format() method formats the specified value or index value and insert them inside the string's placeholder
Try it Yourself:
By Value:
name_of_company = input("Enter the name of the company ")
number_of_units = int(input("how many units do you buy? "))
price_per_unit = int(input("Enter the price of per unit "))
total_price = number_of_units * price_per_unit
print ("You have ordered {} units of the company {}. The total cost of your units is {}
".format(number_of_units,name_of_company,total_price))
Execution of Program:
30 of 73
Try it Yourself:
By Index Value:
name_of_company = input("Enter the name of the company ")
number_of_units = int(input("how many units do you buy? "))
price_per_unit = int(input("Enter the price of per unit "))
total_price = number_of_units * price_per_unit
print ("You have ordered {0} units of the company {1}. The total cost of your units is {2}
".format(number_of_units,name_of_company,total_price))
Execution of Program:
F String:
We can also format the string using the word ‘f’ before starting our message.
Try it Yourself:
name = 'John Doe'
print(f'my name is {name}')
Execution of Program:
4.5 Typecasting in Python:
With the help of typecasting, we change the type of a value. It can be float, integer, string or could be anything as per our
requirement. We use the ‘type()’ function to determine the type of value. The following are the functions we can use to typecast
a value.
31 of 73
Try it Yourself:
number = 1
type(number) # type function shows the type of our value.
number = str(number)Number
type(number)
Execution of Program:
32 of 73
Chapter 5:
5.1 Basic Data Structure in Python:
Although, Python follows the large number of data structures, but the most basic ones are:
String
List
Tuple
Dictionary
Set or Sets
33 of 73
String:
Any message in python surrounded by either single quotation marks, or double quotation marks. The index number ranges from
0 to the last element, which is referred to as the positive index. Negative indexing, which begins at -1, allows you to reach
elements from last to first.
Creating a String:
With single quotation marks: 'hello'
With double quotation marks: "hello".
With triple quotation marks: """ hello """.
Try it Yourself:
'Hello World' # With Single Quotations
"Hello World" # With Double Quotations
'''Hello World''' # With Triple Single Quotations
"""Hello World""" # With Triple Double Quotations
Execution of Program:
Method for String:
Strings in python has a set of built-in methods:
34 of 73
35 of 73
36 of 73
List:
Lists are used to sequentially hold data of various data types. Every element of the list has an address given to it, which is known
as the Index. The index number ranges from 0 to the last element, which is referred to as the positive index. Negative indexing,
which begins at -1, allows you to reach elements from last to first. A list is a collection which is ordered, changeable or mutable,
and allows duplicates.
Creating a List:
We can create a list using Index brackets ‘[]’. Lists are by-default empty when created.
Try it Yourself:
List1 = []
Execution of Program:
Operations:
We can also perform underneath operations on List.
Try it Yourself:
List = ['Name', 12, 13.5, True] # Types of values we can store while creating in a List:
List[0:3] # Slicing a list
List[0] # Accessing first element of List
List[-1] # Accessing Last element of List
del List # Deleting a List
List2 = ['Name', 12, 13.5, True] # Creating a new List
Remainder: You can recreate the list with the same name as the last one.
List2[1] = 'Twelve' # Change Item Value
len(List2) # We can also count that how many elements are there in the list
37 of 73
Execution of Program:
Method for List:
List in python has a set of built-in methods:
38 of 73
Tuple:
Tuples are used to store multiple items in a single variable. It can also perform many operations and store any type of item just
like List does. But tuple is a collection which is ordered, unchangeable or immutable, and allows duplicates.
Creating a Tuple:
We can create Tuples using the round brackets or ‘()’.
Try it Yourself:
Tuple = ()
print(Tuple)
print(type(Tuple))
Execution of Program:
Operations:
We can also perform underneath operations on Tuple.
Try it Yourself:
Tuple = ('Name', 12, 13.5, True) # Types of values we can store while creating a tuple:
Tuple[0:3] # We can slice a tuple as same as we do it with the list
Tuple[0] # Accessing first element of Tuple
Tuple[-1] # Accessing last element of Tuple
del Tuple # Deleting a Tuple
Tuple2 = ('Name', 12, 13.5, True) # Creating a new Tuple:
Remainder: You can recreate it with the same name as the last one.
Tuple2[1] = 'Twelve' # Tried to change Item Value
Tuple2 # tuple doesn't allow change since it is immutable.
len(Tuple2) # We can also count that how many elements are there in the list
39 of 73
Execution of Program:
Method for Tuple:
Tuples in python has limited built-in methods due to their self-limitations:
40 of 73
Dictionary:
Dictionaries are used to store data values in key: value pairs.
A dictionary is a collection which is ordered, changeable but does not allow duplicates.
Creating a Dictionary:
We can create Dictionary using the curly brackets or ‘{}’.
Try it Yourself:
dictionary = {}
print(dictionary)
print(type(dictionary))
Execution of Program:
Operations:
We can also perform underneath operations on Dictionary.
Try it Yourself:
dictionary['name'] = 'Noah' # Adding a value in empty dictionary
dictionary['age'] = 2
dictionary['age'] = 1.5 #Re-assigning the value
Execution of Program:
Method for Dictionary:
41 of 73
Dictionary has a set of built-in methods:
42 of 73
Set or Sets:
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, does not allow duplicates and unindexed.
Creating a Set:
We can create Set using the curly brackets or ‘{}’, just like we did with the dictionary. We can't create a set with no value,
otherwise it will create a dictionary.
Try it Yourself:
Set = {32,23,42,4,2,2,4,2,1,13}
print(Set)
print(type(Set))
Execution of Program:
Method for Set:
Set has a set of built-in methods:
43 of 73
5.2 Conditional Statements:
Conditional Statements are used to filter the data according to our requirement or checking the condition whether it is true or
not!
IF Statement:
An "if statement" is used to check if the first one is right or not. And written by using the if keyword.
Try it Yourself:
x = 5
If x==5:
print()
Execution of Program:
Remainder:
Before exploring if statement more, let's talk about what is an Indentation and why are using it while writing our code.
Indentation: Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the
indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a
block of code. It could be a four spaces gap, or it could be an eight spaces gap. Use ‘Tab’ Button to indent your code
Try it Yourself:
x = 5
If x==5:
print(x) # 4 spaces gap
x = 5
If x==5:
print(x) # 8 spaces gap
Execution of Program:
44 of 73
ELSE Statement:
An "else statement" is used to check if the last one is right or not. And written by using the else keyword.
Try it Yourself:
x = 5
If x==8:
print(‘Value is 8’)
else:
print(‘Value is 5’)
Execution of Program:
ELIF Statement:
An "elif statement" is used to check if the middle one is right or not. And written by using the elif keyword.
Try it Yourself:
if x == 8:
print('Value is 8')
elif x == 5:
print('Value is 5')
else:
print('No Value Match')
Execution of Program:
45 of 73
NESTED Statement:
Running a condition inside a condition.
Try it Yourself:
x = 5
y = 2
if x == 5:
print('X=5')
if y == 1:
print('Y=1')
else:
print('Y=2')
else:
print('Both are wrong')
Execution of Program:
46 of 73
5.3 Iteration or Looping Statements:
Loop means repeating a process. In Python, it means repeating a process until we get our desired result. Looping is also called
Iteration.
Types of Looping:
There are two main types of loops in Python:
1. For Loop
2. While Loop
For Loop:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Try it Yourself:
for i in 'Python':
print(i)
Execution of Program:
The Range Function:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops
before a specified number.
Try it Yourself:
# range(where to start, where to end, gap in between)
range(10)
Remainder: Range returns a function. We have to convert it into a list to see the values created by the function.
for i in range(10):
print(i, end=' ')
for i in range(2, 10):
print(i, end=' ')
for i in range(2, 10, 2): #By default the gap starts from 1!
print(i, end=' ')
Execution of Program:
47 of 73
48 of 73
Enumerators:
The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that
contains a counter as a key for each value within an object, making items within the collection easier to access.
OR
Enumerate is a built-in function in python that allows you to keep track of the number of iterations (loops) in a loop.
Try it Yourself:
for index, i in enumerate(range(10)):
print('Index value:', index, 'I=',i)
Execution of Program:
Nested For:
Running a for loop inside a for loop.
Try it Yourself:
for i in range(3):
for j in 'Python':
print(j)
print('---' , i , '---')
Execution of Program:
49 of 73
50 of 73
Comprehension in Python:
It is a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using
another sequence.
Types:
There are mainly five types of Comprehensions are there in Python:
1. List Comprehension
2. Tuple Comprehension
3. Dictionary Comprehension
4. Set Comprehension
5. Generator Comprehension
1. List Comprehension:
Performing Comprehension through a list.
Try it Yourself:
List_Comprehension = [x for x in range(5)]
print(List_Comprehension)
Execution of Program:
2. Tuple Comprehension:
Performing Comprehension through a tuple.
Try it Yourself:
Tuple_Comprehension = tuple(x for x in range(5))
print(Tuple_Comprehension)
Execution of Program:
3. Dictionary Comprehension:
Performing Comprehension through a dictionary.
Try it Yourself:
list1 = [x for x in range(5)]
list2 = ['Mon','Tue','Wed','Thu','Fri']
Dictionary_Comprehension ={key:value for (key, value) in zip(list1, list2)}
print(Dictionary_Comprehension)
Execution of Program:
51 of 73
52 of 73
4. Set Comprehension:
Performing Comprehension through sets.
Try it Yourself:
Set_Comprehension = {x for x in range(5)}
print(Set_Comprehension)
Execution of Program:
5. Generator Comprehension:
Generator comprehension is a single-line specification for defining a generator in Python. It is essential to learn this syntax to
write simple and readable code. Note: Generator comprehensions are not the only method for defining generators in Python.
Try it Yourself:
Generator_Comprehension = (i**2 for i in range(10))
print(Generator_Comprehension)
for i in Generator_Comprehension: print(i, end=" ")
Execution of Program:
While Loop:
With the while loop we can execute a set of statements if a condition is true.
Try it Yourself:
string = 'Python'
while string == 'Python':
print(5)
Execution of Program:
53 of 73
Remainder:
It will Keep on running. Killing the terminal in result.
To Stop, follow these steps:
1. Go to Kernel’ and click on Restart and Run All button.
OR
2. Press CTRL + C twice to kill your Jupyter Notebook server.
Counter:
Since, the condition is true. Loop will last infinite. To save ourselves from such a problem, we use a counter for it.
Try it Yourself:
string = 'Python'
i = 0 # counter
while i<5 and string == 'Python':
print(5)
i += 1 # counter
Execution of Program:
Flag:
Flag in Python acts as a signal to the program to determine whether the program as a whole or a specific section of the program
should run. Flag does what counter do. But it takes Boolean value as counter value.
There are two ways to deal with flag operation.
1. Giving a direct Boolean value.
2. Assigning Boolean value to a variable.
54 of 73
1. Giving a direct Boolean value: (Not recommended)
It is mostly not recommended. Although it will stop displaying the output for an instant. Later, it will keep on taking input and
displaying output.
Try it Yourself:
while True: # Flag: Direct Boolean value
message = input("Tell me something cool or Enter 'quit' to end the program: ").lower()
if message == 'quit':
False
else:
print(message)
Execution of Program:
2. Assigning Boolean value to a variable: (Highly recommended)
Try it Yourself:
flag = True
while flag == True: # Flag: Assigning Boolean value to a variable:
message = input("Tell me something cool or Enter 'quit' to end the program: ").lower()
if message == 'quit':
flag = False
else:
print(message)
Execution of Program:
55 of 73
Break:
This keyword can be used to immediately exit a loop, regardless of whether the loop condition has been met. For example, if
you wanted to exit the above while loop early if count reached a certain value, you could add an if statement and a break
keyword inside the loop:
Try it Yourself:
count = 0
while count < 5:
print("Count is", count)
if count == 3:
break
count += 1
Execution of Program:
Continue:
This keyword can be used to immediately move on to the next iteration of a loop, skipping over any remaining code in the
current iteration. For example, if you wanted to skip over the printing of the number 3 in the above while loop, you could add an
if statement and a continue keyword inside the loop:
Try it Yourself:
count = 0
while count < 5:
if count == 3:
count += 1
continue
print("Count is", count)
count += 1
Execution of Program:
56 of 73
Pass:
This keyword can be used as a placeholder when you need to include a statement in your code for syntactic reasons, but you
don't want the statement to do anything. For example, if you wanted to include an empty if statement inside the above while
loop, you could use the pass keyword:
Try it Yourself:
count = 0
while count < 5:
if count == 3:
pass
else:
print("Count is", count)
count += 1
Execution of Program:
Else:
This keyword can be used to add an optional block of code that will run after a loop has finished iterating, but only if
the loop completed normally (i.e., without encountering a break statement). For example, if you wanted to print a
message after the above while loop has finished, you could use the else keyword:
Try it Yourself:
count = 0
while count < 5:
print("Count is", count)
count += 1
else:
print("Loop finished.")
Execution of Program:
57 of 73
58 of 73
5.4 Functions:
Functions are blocks of reusable code that perform a specific task. They are used to break down a large program into smaller,
more manageable chunks of code. Functions help to make the code more modular and easier to read, debug, and maintain.
Functions are defined using the keyword "def".
Try it Yourself:
def greet(name):
print("Hello, " + name + "!")
greet("John")
Execution of Program:
Return:
Return is a keyword used in a function to return a value or expression to the calling program. It terminates the execution of the
function and passes the result back to the caller. If a function does not have a return statement, it returns None by default.
Try it Yourself:
def add(a, b):
return a + b
result = add(2, 3)
print(result)
Execution of Program:
Default parameters:
Default parameters are values assigned to function parameters that are used when the function is called without providing a
value for that parameter. They are specified in the function definition.
Try it Yourself:
def greet(name="World"):
print("Hello, " + name + "!")
greet()
greet("John")
Execution of Program:
59 of 73
60 of 73
Args and Kwargs:
Args and kwargs are special syntaxes used in function definitions to pass a variable number of arguments to a function. Args are
used to pass a variable number of non-keyword arguments, while kwargs are used to pass a variable number of keyword
arguments.
For Args:
Try it Yourself:
def add(*args): # For Args
result = 0
for arg in args:
result += arg
return result
add(3,4,5,5,6)
Execution of Program:
For Kwargs:
Try it Yourself:
def greet(**kwargs): # For Kwargs
for key, value in kwargs.items():
print(f"{key} : {value}")
greet(name="John", age=30)
Execution of Program:
61 of 73
Global vs Local Variable:
Global variables are variables declared outside a function, while local variables are variables declared inside a function. Global
variables can be accessed from anywhere in the program, while local variables are only accessible within the function.
For Local Variable:
Try it Yourself:
def func():
local_var = "local"
print(local_var)
func()
print(local_var)
Execution of Program:
62 of 73
For Global Variable:
1. Declaring the value outside the function:
Try it Yourself:
# Declaring the value outside the function:
global_var = "global"
def func():
print(global_var)
func()
print(global_var)
Execution of Program:
2. Declaring the value inside the function but with global keyword:
Try it Yourself:
# Declaring the value inside the function but with global keyword
def func():
global global_var
global_var = "global"
print(global_var)
func()
print(global_var)
Execution of Program:
63 of 73
Recursion:
Recursion is a technique where a function calls itself to solve a problem. It is useful when a problem can be broken down into
smaller subproblems that can be solved recursively.
Try it Yourself:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1) # Function inside a function
result = factorial(5)
print(result)
Execution of Program:
Lambda function:
Lambda function is a small anonymous function that can have any number of arguments but can only have one expression. They
are useful when you need a short function for a specific task.
Try it Yourself:
add = lambda a, b: a + b
result = add(2, 3)
print(result)
Execution of Program:
64 of 73
Generators:
Generators are functions that allow for the creation of a sequence of values on the fly, without needing to store the entire
sequence in memory at once. They are useful when dealing with large datasets or when generating a sequence of values that
would be too large to store in memory.
Try it Yourself:
def countdown(num):
while num > 0:
yield num
num -= 1
for i in countdown(5):
print(i)
Execution of Program:
65 of 73
6.1 Exceptional Handling:
Chapter 6:
Exception handling is a way to handle errors or exceptional situations that occur during program execution.
o Try,
o Except,
o Finally.
These keywords are used to handle exceptions in Python.
Try:
The try block is used to enclose the code that might raise an exception.
Except:
If an exception is raised, control is transferred to the first matching except block. We can either resolve our issue by selecting
errors one by one or by selecting all throughException as e statement.
Finally:
The finally block is always executed, whether an exception was raised or not.
1. Resolving error one by one:
Try it Yourself:
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is {result}")
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Thank you for using the program!")
Execution of Program:
a. If ‘No error’ received:
b. If ‘error’ received:
66 of 73
2. Resolving through ‘Exception as e’ statement:
Try it Yourself:
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is {result}")
except Exception as e:
print('Invalid Error')
finally:
print("Thank you for using the program!")
Execution of Program:
a. If ‘No error received:
b. If ‘error’ received:
67 of 73
68 of 73
6.2 File Handling:
File:
A file is some information or data which stays in the computer storage devices. You already know about different kinds of file ,
like your music files, video files, text files. Python gives you easy ways to manipulate these files. Generally we divide files in two
categories, text file and binary file. Works fine, even if the cached removes. No more storage consumption or reloading time!
File Handling:
It is the process of working with files in a computer program. Python provides built-in functions to perform file input/output
(I/O) operations, including:
o Open,
o Write,
o Read,
o Append,
o Close.
Open:
The open function is used to open a file in a specified mode (read, write, append, etc.). It returns a file object that can be used to
read from or write to the file. The with statement is often used with open to ensure that the file is automatically closed when it
is no longer needed.
Write:
The write method is used to write data to a file that has been opened for writing. It takes a string argument and writes the string
to the file.
Try it Yourself:
# Writing to a file
with open("example.txt", "w") as f: # Opens the file if exist meanwhile 'w' >> write mode
f.write("Hello, world!") # Creates the file if it does not exist!
Execution of Program:
Read:
The read method is used to read data from a file that has been opened for reading. It returns the contents of the file as a string.
Try it Yourself:
# Reading from a file
with open("example.txt", "r") as f:
data = f.read() # Reads the file if exist meanwhile 'r' >> read mode
print(data)
Execution of Program:
69 of 73
Append:
The append mode can be used with open to open a file for appending. This means that any data written to the file will be added
to the end of the file, rather than overwriting the existing contents. The write method can be used to write data to the file.
Try it Yourself:
# Appending to a file
with open("example.txt", "a") as f:
f.write("\nGoodbye, world!") # Appends text in the file if exist meanwhile 'a' >> append mode
with open("example.txt", "r") as f:
data = f.read()
print(data)
Execution of Program:
70 of 73
Close:
The close method is used to close a file that has been opened with open. It should be called after you are finished working with
the file to free up system resources and prevent data loss.
Seek:
In Python, the seek function is used to change the position of the File Handle to a given specific position. The file handle is like a
cursor, which defines from where the data must be read or written in the file.
Try it Yourself:
with open("example.txt", "r") as f:
f.seek(0) # starts the line from beginning.
data = f.read()
print(data)
f.close() #Closes the file.
Execution of Program:
Remainder: There is no special need to use close() with the open mode.
71 of 73
7.1 CSV File:
Chapter 7:
CSV stands for "comma-separated values" and is a common format for storing and exchanging tabular data. To work with CSV
files in Python, you can use the csv module.
Create a file with named: ‘’whatever.csv’’
Saved this data in it.
Try it Yourself:
import csv # Importing csv formatting into our system.
Execution of Program:
Try it Yourself:
with open("whatever.csv", "w", newline="") as f:
data_handler = csv.writer(f, delimiter=",")
data_handler.writerow(["Year", "Event", "Winner"])
data_handler.writerow(["1995", "Best-Kept Lawn", "None"])
data_handler.writerow(["1999", "Gobstones", "Welch National"])
# Things to remember:
# It's the variable data_handler connected by a dot to the keyword= 'writerow'
with open("whatever.csv", "a", newline="") as f:
data_handler = csv.writer(f, delimiter=",")
data_handler.writerow(["1997", "Best-Kept Lawn2", "NaN"])
data_handler.writerow(["2001", "Gobstones4", "Well2"])
Year,Event,Winner 1995,Best-Kept Lawn,None
1999,Gobstones,Welch National
1997,Best-Kept Lawn2,NaN 2001,Gobstones4,Well2
72 of 73
with open("whatever.csv", "r", newline="") as f:
content2 = csv.reader(f)
for filedata2 in content2:
print(filedata2)
Execution of Program:
7.2 JSON File:
'JSON' stands for 'JavaScript Object Notation'. List of dictionaries. In dict, keys can have a 'numeric' value, but 'JSON'
doesn't support 'numeric' value as key.
Try it Yourself:
import json
Execution of Program:
Try it Yourself:
customer_29876 = {
"first_name": "David",
"last_name": "Elliott",
"address": "4803 Wellesley St.",
}
with open("customer_29876.json", "w") as f:
json.dump(customer_29876, f)
with open("customer_29876.json", "r") as f:
print(json.load(f))
Execution of Program:
73 of 73